package edu.jmu.transmissionassistant.controller

import android.os.Build
import androidx.annotation.RequiresApi
import com.yanzhenjie.andserver.annotation.*
import com.yanzhenjie.andserver.http.multipart.MultipartFile
import com.yanzhenjie.andserver.util.MediaType
import edu.jmu.transmissionassistant.App
import edu.jmu.transmissionassistant.component.AppConfig
import edu.jmu.transmissionassistant.component.MessageBus
import edu.jmu.transmissionassistant.component.launch
import edu.jmu.transmissionassistant.model.UploadFileInfo
import edu.jmu.transmissionassistant.util.JsonUtils
import edu.jmu.transmissionassistant.util.Logger
import kotlinx.coroutines.Dispatchers
import java.time.LocalDateTime
import java.util.*

@Controller
@RequestMapping("/upload")
class UploadController {

    @RequiresApi(Build.VERSION_CODES.O)
    @ResponseBody
    @CrossOrigin(methods = [RequestMethod.POST])
    @PostMapping(
        "/",
        produces = [MediaType.APPLICATION_JSON_UTF8_VALUE],
        consumes = [MediaType.MULTIPART_FORM_DATA_VALUE]
    )
    fun upload(@RequestParam("file") file: MultipartFile): String {
        val fileName = file.filename ?: UUID.randomUUID().toString()
        try {
            val dir = App.mInstance!!.mRootDir!!
                .resolve(AppConfig.UPLOAD_PATH)
                .resolve(fileName)
            Logger.i("upload file to ${dir.path}")
            file.transferTo(dir)
        } catch (e: Exception) {
            e.printStackTrace()
            return JsonUtils.failedJson(400, e.message)
        }
        launch(Dispatchers.IO, tryBlock = {

            MessageBus.instance().publish(AppConfig.UPLOAD_PATH, UploadFileInfo(fileName, LocalDateTime.now()))
        }, catchBlock = {
            it.printStackTrace()
        })
        return JsonUtils.successfulJson("ok")
    }

    @GetMapping("/")
    fun index(): String {
        return "forward:/page/index.html"
    }
}